<template>
    <a-card style="padding: 0px">
        <a-form style="margin:0,0" :form="form" @submit="handleSubmit">

            <a-form-item v-bind="formItemLayout" label="会员名">
                <a-input
                        v-decorator="[
          'username',
          {
            rules: [
            { required: true, message: '请输入您的会员名!' },
            {
              validator: validUserName,
            }],
          }
        ]"
                        style="width: 100%"
                ></a-input>
            </a-form-item>
            <a-form-item has-feedback v-bind="formItemLayout" label="密码">
                <a-input
                        v-decorator="[
          'password',
          {
            rules: [{
              required: true, message: '请输入密码!',
            }, {
              validator: validateToNextPassword
            }],
          }
        ]"
                        type="password"
                />
            </a-form-item>
            <a-form-item has-feedback v-bind="formItemLayout" label="确认密码">
                <a-input
                        v-decorator="[
          'confirm',
          {
            rules: [{
              required: true, message: '请输入确认密码!',
            }, {
              validator: compareToFirstPassword,
            }],
          }
        ]"
                        type="password"
                        @blur="handleConfirmBlur"
                />
            </a-form-item>


            <a-form-item v-bind="formItemLayout" label="手机号">
                <a-input
                        v-decorator="[
          'mobile',
          {
            rules: [
            { required: true, message: '请输入您的手机号!' },
            {
              validator: validPhone,trigger:'change'
            }],
          }
        ]"
                        style="width: 100%"
                ></a-input>
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="验证码">
                <a-input
                        v-decorator="[
          'code',
          {
            rules: [
            { required: true, message: '请输入验证码!' }],
          }
        ]"
                        style="width: 100%"
                        @blur="handleCodeBlur"
                ></a-input>
                <a-button type="primary" @click="fetchCode" :disabled="!isStop">{{sendcodeMsg}}</a-button>
            </a-form-item>
            <a-form-item v-bind="tailFormItemLayout">
                <a-button style="width: 200px" type="primary" html-type="submit">注册</a-button>
            </a-form-item>
        </a-form>
    </a-card>
</template>

<script>


    import loginApi from "../../../api/login";
    import userApi from "../../../api/user/userApi";

    export default {
        name: "memberRegister",
        data() {
            return {
                isStop: true, //是否倒计时结束
                sendcodeMsg: "获取验证码", //发送验证码按钮文字
                confirmDirty: false,
                code: "", //验证码
                formItemLayout: {
                    labelCol: {
                        xs: {span: 12},
                        sm: {span: 7},
                    },
                    wrapperCol: {
                        xs: {span: 12},
                        sm: {span: 10},
                    },
                },
                tailFormItemLayout: {
                    wrapperCol: {
                        xs: {
                            span: 24,
                            offset: 1,
                        },
                        sm: {
                            span: 24,
                            offset: 8,
                        },
                    },
                },
            };
        },
        beforeCreate() {
            this.form = this.$form.createForm(this, {name: 'register'});
        },
        methods: {
            handleSubmit(e) {
                e.preventDefault();
                this.form.validateFieldsAndScroll((err, values) => {
                    if (!err) {
                        delete values.confirm
                        userApi.memberRegister(values).then(resp => {
                            if (resp.data.flag) {
                                this.$message.success("注册成功")
                                this.$router.push("/login")
                            }
                        })
                    }
                });
            },
            /**
             * 获取验证码
             */
            fetchCode() {
                const mobile = this.form.getFieldValue("mobile");
                if (!mobile || mobile.trim()===""){
                    this.$message.warning("请先填写手机号");
                    return;
                }
                let seconds = 10;
                this.isStop = false;

                const that = this; //在setInterval中，this不是vue实例，需要使用that转一下

                loginApi.fetchCheckCode(mobile).then(resp => {
                    if (resp.data.flag) {
                        this.$message.success(resp.data.message, 1);
                        let id = setInterval(function () {
                            that.sendcodeMsg = seconds + "秒后可再次获取";
                            if (seconds === 0) {
                                clearInterval(id);
                                that.sendcodeMsg = "点击获取验证码";
                                that.isStop = true;
                            }
                            seconds--;
                        }, 1000);
                    } else {
                        that.sendcodeMsg = "点击获取验证码";
                        that.isStop = true;
                    }
                });
            },

            handleConfirmBlur(e) {
                const value = e.target.value;
                this.confirmDirty = this.confirmDirty || !!value;
            },
            compareToFirstPassword(rule, value, callback) {
                const form = this.form;
                if (value && value !== form.getFieldValue('password')) {
                    callback("两次密码输入不一致");
                } else {
                    callback();
                }
            },
            validateToNextPassword(rule, value, callback) {
                const form = this.form;
                if (value.length < 4) {
                    callback('密码长度不能低于4位');
                }
                if (value && this.confirmDirty) {
                    form.validateFields(['confirm'], {force: true});
                }
                callback();
            },
            /**
             * 校验登录名
             */
            validUserName(rule, value, callback) {
                /* if (!/[A-Za-z0-9_\-\u4e00-\u9fa5]+/.test(value)) {
                     return callback(new Error("用户名格式不正确"));
                 } else {
                     callback();
                 }*/
                if (value.length > 12 || value.length < 4) {
                    return callback(new Error("用户名长度应在4到12之间"));
                } else {
                    callback();
                }
            },
            /**
             * 校验手机号
             */
            validPhone(rule, value, callback) {
                if (!/^1[3456789]\d{9}$/.test(value)) {
                    return callback(new Error("手机号格式不正确"));
                } else {
                    callback();
                }
            },
            /**
             * 注册时验证码离焦事件
             */
            handleCodeBlur(e) {
                this.code = e.target.value;
            },


        },
    };
</script>